package com.hxh.util;

import cn.hutool.json.JSONObject;
import com.hxh.entity.output.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.Objects;

@Slf4j
public class Common {

    public static boolean hasPropertyChanged(Object oldObj, Object newObj, String... fieldNames) {
        if (oldObj == null && newObj == null) {
            return false;
        }
        if (oldObj == null || newObj == null) {
            return true;
        }
        for (String fieldName : fieldNames) {
            try {
                Field field = oldObj.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                Object oldValue = field.get(oldObj);
                Object newValue = field.get(newObj);
                if (!Objects.equals(oldValue, newValue)) {
                    return true;
                }
            } catch (Exception e) {
                log.warn("无法比较字段: {}", fieldName);
            }
        }
        return false;
    }


    public static String getStringNotNull(String str1, String str2) {
        if (StringUtils.isNotBlank(str1)) {
            return str1;
        } else {
            return str2;
        }
    }


    public static void returnApiResult(HttpServletResponse response, ApiResult apiResult) {
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        try (PrintWriter out = response.getWriter()) {
            JSONObject jsonObject = new JSONObject(apiResult);
            out.write(jsonObject.toString());
            out.flush();
        } catch (IOException ignored) {
        }
    }
}
